<script lang="ts" setup>
import useCategoryStore from "../../../store/modules/category.ts";
import {nextTick, onBeforeUnmount, reactive, ref, watch} from "vue";
import type {Attr, AttrValue} from "../../../api/product/attr/type.ts";
import {reAddOrUpdateAttr, reqRemoveAttr} from "../../../api/product/attr";
import { ElMessage } from 'element-plus';

const categoryStore = useCategoryStore();
let scene = ref<number>(0);
const attrParams = reactive<Attr>({
  attrName: "",
  attrValues: [],
  category3Id: ""
});
const arr = ref<any>([]);

//监听仓库三级分类ID变化
watch(
    () => categoryStore.c3Id,
    () => {
      //清空上一次查询的属性与属性值
      categoryStore.attrArr.length = 0;
      //保证三级分类得有才能发请求
      if (!categoryStore.c3Id) return
      //获取分类的ID
      categoryStore.getAttr()
    },
)

const addAttr = () => {
  attrParams.category3Id = categoryStore.c3Id;
  scene.value = 1;
}

const updateAttr = (row: Attr) => {
  scene.value = 1;
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
}

const cancel = () => {
  scene.value = 0;
}

const addAttrValue = () => {
  attrParams.attrValues.push({
    valueName: '',
    flag: true
  });
  nextTick(() => {
    // 确保元素存在再调用focus
    if (arr.value && arr.value.length > 0) {
      const lastInput = arr.value[arr.value.length - 1];
      if (lastInput) {
        lastInput.focus();
      }
    }
  })
}

const save = async () => {
  const result = await reAddOrUpdateAttr(attrParams);

  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: attrParams.id ? "更新成功" : "添加成功"
    });
    await categoryStore.getAttr();

    Object.assign(attrParams, {
      attrName: "",
      attrValues: [],
      category3Id: "",
    });

    scene.value = 0;
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "更新失败" : "添加失败"
    });
  }
}

const toEdit = (row: AttrValue, index: number) => {
  //如果内容为空，不失焦
  // 确保 row.valueName 存在再调用 trim()
  if (!row.valueName || row.valueName.trim() === '') {
    ElMessage({
      type: "error",
      message: "内容为空"
    });

    attrParams.attrValues = attrParams.attrValues.filter((_, i) => index !== i);

    return;
  }

  //如果内容重复，不失焦
  let isFlag = attrParams.attrValues.find((item) => {
    if (item !== row && item.valueName) {
      return item.valueName === row.valueName;
    }
  });

  //重复就终止方法
  if (isFlag) {
    ElMessage({
      type: "error",
      message: "哒唛，不能重复"
    })
    return;
  }

  row.flag = false;
}

const toLook = (row: AttrValue, index: number) => {
  row.flag = true;
  nextTick(() => {
    // 确保元素存在再调用focus
    if (arr.value[index]) {
      arr.value[index].focus();
    }
  });
}

const removeAttrValue = async (index: number) => {
  // 删除指定索引的属性值
  attrParams.attrValues = attrParams.attrValues.filter((_,i) => index !== i);

  // 如果还有属性值，更新属性
  if (attrParams.attrValues.length > 0) {
    const result = await reAddOrUpdateAttr(attrParams);
    if (result.code === 200) {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
    } else {
      ElMessage({
        type: "error",
        message: "删除失败"
      });
    }
  } else {
    // 如果没有属性值了，清除表单并返回列表视图
    Object.assign(attrParams, {
      attrName: "",
      attrValues: [],
      category3Id: "",
    });
    scene.value = 0;
  }
}

const removeAttr = async (id: number) => {
  const result = await reqRemoveAttr(id);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功"
    });
    // 删除成功后重新获取属性列表
    categoryStore.attrArr.length = 0;
    await categoryStore.getAttr();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败"
    });
  }
}

onBeforeUnmount(() => {
  categoryStore.$reset();
})
</script>

<template>
  <Category :scene="scene"/>
  <el-card style="margin: 10px 0">
    <div v-show="scene === 0">
      <el-button :disabled="!categoryStore.c3Id" icon="Plus" size="default" type="primary" @click="addAttr">添加属性
      </el-button>
      <el-table :data="categoryStore.attrArr" border style="margin: 10px 0">
        <el-table-column align="center" label="序号" type="index" width="80px"></el-table-column>
        <el-table-column label="属性名称" width="120px">
          <template #default="{row}">
            <pre>{{ row.attrName }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="属性值名称">
          <template #default="{row}">
            <el-tag v-for="(item) in row.attrValues" :key="item.id" style="margin: 5px">{{ item.valueName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template #default="{row}">
            <el-button icon="Edit" type="warning" @click="updateAttr(row)"></el-button>
            <el-popconfirm :title="`确定删除${row.attrName}`" icon="Delete" @confirm="removeAttr(row.id)">
              <template #reference>
                <el-button icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="scene === 1">
      <el-form inline>
        <el-form-item :label="'添加属性名'">
          <el-input v-model="attrParams.attrName" placeholder="输入属性名"></el-input>
        </el-form-item>
      </el-form>
      <el-button :disabled="!attrParams.attrName" icon="Plus" size="default" type="primary" @click="addAttrValue">
        添加属性
      </el-button>
      <el-button size="default" type="info" @click="cancel">取消</el-button>
      <el-table :data="attrParams.attrValues" border style="margin: 10px 0">
        <el-table-column label="序号" type="index" width="80px"></el-table-column>
        <el-table-column label="属性值">
          <template #default="{row, $index}">
            <el-input :ref="(vc: any) => arr[$index] = vc" v-if="row.flag" v-model="row.valueName" placeholder="输入属性值" @blur="toEdit(row, $index)"></el-input>
            <div v-else @click="toLook(row, $index)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{row, $index}">
            <el-popconfirm :title="`确定删除${row.attrValue}`" @confirm="removeAttrValue($index)" icon="Delete">
              <template #reference>
                <el-button icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="save" :disabled="attrParams.attrValues.length === 0">保存</el-button>
      <el-button type="info" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>

</style>